<template>
  <div class="page-container">
    <h2 class="page-title">我的优惠券</h2>
    <div class="coupon-list">
      <el-empty v-if="coupons.length === 0" description="暂无优惠券" />
      <el-card v-for="c in coupons" :key="c.id" class="coupon" shadow="hover">
        <div class="coupon-info">
          <div class="name">{{ c.name }}</div>
          <div class="desc">{{ renderDesc(c) }}</div>
          <div class="time">有效期至 {{ formatDate(c.expiresAt) }}</div>
        </div>
        <el-tag :type="statusTagType(c.status)">{{ statusText(c.status) }}</el-tag>
      </el-card>
    </div>
  </div>
</template>
<script setup>
import { onMounted, ref } from 'vue'
import { userApi } from '@/api/user'
import { useUserStore } from '@/store/modules/user'
import { ElMessage } from 'element-plus'

const coupons = ref([])

const renderDesc = (c) => {
  if (c.discountType === 1) return `满${c.minAmount}减${c.discountValue}`
  if (c.discountType === 2) return `满${c.minAmount}折扣${c.discountValue}%`
  return ''
}

const formatDate = (d) => {
  if (!d) return ''
  const t = new Date(d)
  const y = t.getFullYear()
  const m = String(t.getMonth() + 1).padStart(2, '0')
  const dd = String(t.getDate()).padStart(2, '0')
  return `${y}-${m}-${dd}`
}

const statusText = (s) => (s === 0 ? '未使用' : s === 1 ? '已使用' : '已过期')
const statusTagType = (s) => (s === 0 ? 'success' : s === 1 ? 'info' : 'danger')

const userStore = useUserStore()
onMounted(async () => {
  if (!userStore.isLoggedIn) {
    userStore.showLoginModal = true
    ElMessage.error('请先登录后查看优惠券')
    return
  }
  try {
    const res = await userApi.getUserCoupons()
    coupons.value = res?.data?.coupons ?? []
  } catch {
    ElMessage.error('获取优惠券失败')
  }
})
</script>
<style scoped>
.page-container { max-width: 900px; margin: 0 auto; padding: var(--spacing-xl); }
.page-title { font-size: var(--font-size-xl); font-weight: var(--font-weight-bold); margin-bottom: var(--spacing-lg); }
.coupon-list { display: flex; flex-direction: column; gap: var(--spacing-md); }
.coupon { display: flex; justify-content: space-between; align-items: center; }
.coupon-info { display: flex; flex-direction: column; gap: 4px; }
.name { font-weight: var(--font-weight-medium); }
.desc { color: var(--primary-color); }
.time { color: var(--text-secondary); font-size: var(--font-size-xs); }
</style>